package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.common.utils.R;
import com.atguigu.gulimall.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SecKillService;
import com.atguigu.gulimall.seckill.to.SecKillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SecKillSessionWithSkus;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.logging.log4j.util.Strings;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: xuesm
 * @date: 2025/3/14 22:45
 */
@Service
public class SecKillServiceImpl implements SecKillService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    private final String SESSION_CACHE_PREFIX="seckill:session:";
    private final String SKUKILL_CACHE_PREFIX="seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE="seckill:stock:"; // + 随机码

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = ops.get(killId);
        if (Strings.isEmpty(json)){
            return null;
        }else {
            SecKillSkuRedisTo redis = JSON.parseObject(json, SecKillSkuRedisTo.class);
            // 校验合法性
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long time = new Date().getTime();
            long ttl = endTime - time;
            // 校验抢购时间
            if (time >= startTime && time <= endTime){
                // 校验随机码
                String randomCode = redis.getRandomCode();
                String redisKilled = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (key.equals(randomCode) && killId.equals(redisKilled)){
                    // 校验购买数量
                    if (num <= redis.getSeckillCount()){
                        // 校验幂等性，是否购买过， 防止重复购买， redis setnx 占位
                        String mKey = memberRespVo.getId() + "_" + redis.getSkuId();
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(mKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean){
                            // 从来没有购买过 看还能买不
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            try {
                                semaphore.acquire(num);
                                String timeId = IdWorker.getTimeId();
                                return timeId;
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    @Override
    public SecKillSkuRedisTo getSkuSecKillInfo(Long skuId) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if (keys != null && keys.size() > 0){
            for (String key : keys) {
                if (key.endsWith("_" + skuId)){
                    String json = ops.get(key);
                    SecKillSkuRedisTo redis = JSON.parseObject(json, SecKillSkuRedisTo.class);
                    // 如果没有在秒杀期间需要隐藏随机码
                    long time = new Date().getTime();
                    Long startTime = redis.getStartTime();
                    Long endTime = redis.getEndTime();
                    if (time >= startTime && time <= endTime){

                    }else {
                        redis.setRandomCode(null);
                    }
                    return redis;
                }
            }
        }
        return null;
    }

    @Override
    public List<SecKillSkuRedisTo> getCurrentSecKillSkus() {
        long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSION_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            long startTime = Long.parseLong(s[0]);
            long endTime = Long.parseLong(s[1]);
            if (time >= startTime && time<=endTime){
                List<String> range = redisTemplate.opsForList().range(key,0, -1);
                BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = ops.multiGet(range);
                if (list != null){
                    List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                        SecKillSkuRedisTo redis = JSON.parseObject(item, SecKillSkuRedisTo.class);
                        return redis;
                    }).collect(Collectors.toList());
                    return collect;
                }
            }
        }
        return null;
    }

    @Override
    public void uploadSecKillSkuLast3Days() {
        R session = couponFeignService.getLate3DaysSession();
        if (session.getCode() == 0){
            List<SecKillSessionWithSkus> list = session.getData(new TypeReference<List<SecKillSessionWithSkus>>() {
            });
            // 缓存活动信息
            saveSessionInfos(list);
            // 缓存活动关联商品信息
            saveSessionSkuInfos(list);
        }
    }


    private void saveSessionInfos(List<SecKillSessionWithSkus> list) {
        list.stream().forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime+"_"+endTime;
            Boolean flag = redisTemplate.hasKey(key);
            if (Boolean.FALSE.equals(flag)){
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" +item.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }


    private void saveSessionSkuInfos(List<SecKillSessionWithSkus> list) {
        list.stream().forEach(session -> {
            BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(secKillSkuVo -> {
                String randomCode = UUID.randomUUID().toString().replace("-", "");

                if (Boolean.FALSE.equals(ops.hasKey(secKillSkuVo.getPromotionSessionId().toString() + "_" + secKillSkuVo.getSkuId().toString()))){
                    SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
                    // 1. sku基本数据
                    R r = productFeignService.getSkuInfo(secKillSkuVo.getSkuId());
                    if (r.getCode() == 0){
                        SkuInfoVo skuInfo = r.get("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(skuInfo);
                    }
                    // 2. sku秒杀信息
                    BeanUtils.copyProperties(secKillSkuVo, redisTo);
                    // 开始时间、结束时间、随机码
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    redisTo.setRandomCode(randomCode);

                    // 使用库存作为分布式的信号量 限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                    // 商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(secKillSkuVo.getSeckillCount());

                    String jsonString = JSON.toJSONString(redisTo);
                    ops.put(secKillSkuVo.getPromotionSessionId() + "_" + secKillSkuVo.getSkuId().toString(), jsonString);
                }


            });
        });
    }


}
